﻿using Newtonsoft.Json;
using Paas.Pioneer.IOTNetworkCard.RequestFactory.Context;
using Paas.Pioneer.IOTNetworkCard.RequestFactory.Context.Enum;
using Paas.Pioneer.IOTNetworkCard.RequestFactory.Dto.Input;
using Paas.Pioneer.IOTNetworkCard.RequestFactory.Dto.Output;
using System.Net;
using System.Text;
using System.Xml;
using Microsoft.Extensions.Logging;
using Volo.Abp;
using Volo.Abp.DependencyInjection;

namespace Paas.Pioneer.IOTNetworkCard.RequestFactory.Factory
{
    public class TelecomRequestService : IRequestFactory, ISingletonDependency
    {
        private readonly HttpClient _httpClient;
        private readonly ILogger<TelecomRequestService> _logger;
        private string _baseUrl = "http://api.ct10649.com:9001/m2m_ec/query.do";
        private string _appbaseUrl = "http://api.ct10649.com:9001/m2m_ec/app/serviceAccept.do";

        public TelecomRequestService(IHttpClientFactory httpClientFactory, ILogger<TelecomRequestService> logger)
        {
            _logger = logger;
            _httpClient = httpClientFactory.CreateClient();
        }

        public EContextRequestType Type => EContextRequestType.Telecom;

        #region 停机保号/复机/测试期去激活

        /// <summary>
        /// 停机保号/复机/测试期去激活
        /// </summary>
        /// <param name="disabledNumberDto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<DisabledNumberOutDto?> DisabledNumberAsync(DisabledNumberDto disabledNumberDto)
        {
            var url =
                $"{_baseUrl}?method={disabledNumberDto.Method}&user_id={disabledNumberDto.Account}&access_number={disabledNumberDto.AccessNumber}&acctCd={disabledNumberDto.AcctCd}&passWord={disabledNumberDto.DesPassword}&sign={disabledNumberDto.Sign}&orderTypeId={disabledNumberDto.OrderTypeId}";

            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("DisabledNumberAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<DisabledNumberOutResponseDto>(resultJson)?.BusinessServiceResponse;
        }

        #endregion

        #region 机卡重绑

        /// <summary>
        /// 机卡重绑
        /// </summary>
        /// <param name="iMEIReRecOrdDto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<IMEIReRecOrdDtoOutDto?> IMEIReRecOrdAsync(IMEIReRecOrdDto iMEIReRecOrdDto)
        {
            var url =
                $"{_appbaseUrl}?method={iMEIReRecOrdDto.Method}&action={iMEIReRecOrdDto.Action}&access_number={iMEIReRecOrdDto.AccessNumber}&user_id={iMEIReRecOrdDto.Account}&passWord={iMEIReRecOrdDto.DesPassword}&sign={iMEIReRecOrdDto.Sign}";

            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("IMEIReRecOrdAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<IMEIReRecOrdDtoOutDto>(resultJson);
        }

        /// <summary>
        /// 流量总使用量查询(时间段)
        /// </summary>
        /// <param name="queryTrafficByDateDto"></param>
        /// <returns></returns>
        public async Task<QueryTrafficByDateOutDto?> QueryTrafficByDateAsync(QueryTrafficByDateDto queryTrafficByDateDto)
        {
            var url =
            $"{_baseUrl}?method={queryTrafficByDateDto.Method}&access_number={queryTrafficByDateDto.AccessNumber}&user_id={queryTrafficByDateDto.Account}&passWord={queryTrafficByDateDto.DesPassword}&sign={queryTrafficByDateDto.Sign}&startDate={queryTrafficByDateDto.StartDate}&endDate={queryTrafficByDateDto.EndDate}&needDtl={queryTrafficByDateDto.NeedDtl}";

            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("QueryTrafficByDateAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<QueryTrafficByDateResonOutDto>(resultJson)?.root;
        }

        #endregion

        #region 获取卡实名信息

        /// <summary>
        /// 获取卡实名信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<SvcContQueryIotRealNameDto?> QueryIotRealNameAsync(QueryIotRealNameInput input)
        {
            var url =
                $"{_baseUrl}?method={input.Method}&access_number={input.AccessNumber}&user_id={input.Account}&passWord={input.DesPassword}&sign={input.Sign}";
            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("QueryIotRealNameAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<SvcContQueryIotRealNameDto>(resultJson);
        }

        #endregion

        #region 接入号码查询接口
        /// <summary>
        /// 接入号码查询接口
        /// </summary>
        /// <param name="getTelephoneDto"></param>
        /// <returns></returns>
        public async Task<GetTelephoneOutDto?> GetTelephoneAsync(GetTelephoneDto input)
        {
            var url =
                 $"{_baseUrl}?method={input.Method}&iccid={input.ICCID}&user_id={input.Account}&passWord={input.DesPassword}&sign={input.Sign}";

            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("GetTelephoneAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<GetTelephoneOutDto>(resultJson);
        }
        #endregion

        #region 产品资料查询接口
        /// <summary>
        /// 产品资料查询接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ProdInstQueryOutDto> ProdInstQueryAsync(ProdInstQueryDto input)
        {
            var url =
               $"{_baseUrl}?method={input.Method}&user_id={input.Account}&access_number={input.AccessNumber}&passWord={input.DesPassword}&sign={input.Sign}";

            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("ProdInstQueryAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<ProdInstQueryOutDto>(resultJson);
        }

        #endregion

        #region 欠费查询接口
        /// <summary>
        /// 欠费查询接口
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<QueryOweOutDto> QueryOweAsync(QueryOweDto input)
        {
            var url =
              $"{_baseUrl}?method={input.Method}&user_id={input.Account}&access_number={input.AccessNumber}&passWord={input.DesPassword}&sign={input.Sign}";

            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("QueryOweAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<QueryOweOutDto>(resultJson);
        }
        #endregion

        /// <summary>
        /// SIM卡列表查询接口
        /// </summary>
        /// <param name="getSIMListDto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<GetSIMListOutDto> GetSIMListAsync(GetSIMListDto input)
        {
            var url =
              $"{_baseUrl}?method={input.Method}&pageIndex={input.pageIndex}&access_number={input.AccessNumber}&iccid={input.ICCID}" +
              $"&activationTimeBegin={input.activationTimeBegin}&activationTimeEnd={input.activationTimeEnd}" +
              $"&simStatus={input.simStatus}&groupId={input.groupId}&user_id={input.Account}&passWord={input.DesPassword}&sign={input.Sign}";

            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("GetSIMListAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<GetSIMListOutDto>(resultJson);
        }

        /// <summary>
        /// 流量总使用量查询(当月)
        /// </summary>
        /// <param name="queryTrafficInput"></param>
        /// <returns></returns>
        public async Task<QueryTrafficOutDto> QueryTrafficAsync(QueryTrafficDto input)
        {
            var url =
            $"{_baseUrl}?method={input.Method}&access_number={input.AccessNumber}&user_id={input.Account}&passWord={input.DesPassword}&sign={input.Sign}&needDtl={input.NeedDtl}";

            var resultXml = await _httpClient.GetStringAsync(url);
            if (resultXml.IsNullOrEmpty())
            {
                return null;
            }

            string resultJson = string.Empty;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXml);
                resultJson = JsonConvert.SerializeXmlNode(doc);
            }
            catch (Exception e)
            {
                _logger.LogError("QueryTrafficAsync =>url: {url}，resultJson：{resultJson}", e);
            }

            if (resultJson.IsNullOrEmpty())
            {
                return null;
            }

            return JsonConvert.DeserializeObject<QueryTrafficOutDtoResonOutDto>(resultJson)?.root;
        }
    }
}